﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Hangjing.Weixin;
using Hangjing.Model;
using Hangjing.SQLServerDAL;
using Hangjing.Common;

namespace Html5.Account
{
    /// <summary>
    /// 微信授权回调界面
    /// </summary>
    public partial class weixincallbak : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string returnurl = WebUtility.FixgetCookie("reurl");
            if (Request["code"] != null)
            {
                string code = Request["code"];
                WebOAuth wo = new WebOAuth(Context, code);

                string openid = "";

                string state = HjNetHelper.GetQueryString("state");
                if (state != "hj") //说明是获取具体城市的公众号对应的openid
                {
                    openid = wo.getOpenid(Convert.ToInt32(state));
                }
                else
                {
                    openid = wo.getOpenid();
                    weixinUserInfo wxuser = wo.GetUserInfoByUnionID(Context, openid);
                    string nickname = "";
                    if (wxuser.subscribe != "0")
                    {
                        nickname = wxuser.nickname;
                    }

                    ECustomer dal = new ECustomer();
                    int userid = dal.addByOpenid(nickname, openid);

                    WebUtility.FixsetCookie("openid", openid, 365);
                }

                HJlog.toLog("state=" + state + "\r\nreturnurl=" + returnurl);


                if (returnurl != null && returnurl != "")
                {
                    if (returnurl.IndexOf("?") > 0)
                    {
                        returnurl += "&openid=" + openid;
                    }
                    else
                    {
                        returnurl += "?openid=" + openid;
                    }

                    Response.Redirect(returnurl);

                }
                else
                {
                    Response.Redirect("/TogoList.aspx?nourl");
                }


            }
            else
            {
                Response.Write("授权失败,请重试");
            }

        }
    }
}